import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { Modal, message, Form, Input, Radio } from 'antd';
import { PageContainer } from '@ant-design/pro-components';
import { supplycouponSearch, supplycouponSupply, supplycouponCheck } from '@/services/place';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';
import StorageManager from '@/utils/StorageManager';

import styles from './style.less';
import { isEmpty } from 'lodash';

const SensitizeManageList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [modalNumForm] = Form.useForm();
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const [modelNumVisible, setModelNumVisible] = useState<boolean>(false);
  const [modelText, setModelText] = useState<string>('');
  const [modelTitle, setModelTitle] = useState<string>('');
  const [isCouponFalg, setIsCouponFalg] = useState<boolean>(false); // 判断是不是预付券

  const authorization: any = StorageManager.getLocalStorageSync('authorization') || [];

  // 提交
  const handleOperate = async (record: any, type: string) => {
    if (type === '补券') {
      modalNumForm.setFieldsValue({
        activityId: record.activityId || '',
        placeChannelId: record.placeChannelId || '',
        activity: record.activity || '',
        salePrice: '',
        discount: '',
        mobile: '',
        advanceStartTime: false,
      });
      setIsCouponFalg(record.priceCouponFlag);
      setModelTitle('用户补券');
      setModelText('确认补券');
      setModelNumVisible(true);
      return;
    }
    if (type === '验证发放') {
      modalNumForm.setFieldsValue({
        activityId: record.activityId || '',
        placeChannelId: record.placeChannelId || '',
        activity: record.activity || '',
        mobile: '',
      });
      setIsCouponFalg(false);
      setModelTitle('验证发放');
      setModelText('确认验证');
      setModelNumVisible(true);
      return;
    }
  };

  const getAuthorization = () => {
    const flag = authorization.find((i: any) =>
      ['ROLE_SupplyCouponL1', 'ROLE_SupplyPriceCoupon', 'ROLE_SupplyCoupon'].includes(i.authority),
    );
    return !isEmpty(flag);
  };

  const columns: ProColumns<API.SupplycouponListItem>[] = [
    // 表单
    {
      title: '活动定义',
      dataIndex: 'activityId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '活动定义',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动代码',
      dataIndex: 'activityCode',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券名',
      dataIndex: 'activity',
      ellipsis: true,
      width: 190,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      dataIndex: 'activityStartTime',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'activityEndTime',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '补券',
      dataIndex: 'operation',
      width: 80,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record: any) {
        return (
          <div key={record.id}>
            {[-3, -2, -1, 0, 1, 102, 104].includes(record.needGenAsynFile) &&
              getAuthorization() && (
                <>
                  <a onClick={() => handleOperate(record, '补券')}>补券</a>&nbsp;&nbsp;
                  <a onClick={() => handleOperate(record, '验证发放')}>验证发放</a>&nbsp;&nbsp;
                </>
              )}
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: any = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await supplycouponSearch(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: rows,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  const handleNumOK = () => {
    modalNumForm.validateFields().then(async (values) => {
      setConfirmLoad(true);
      const fatchApi = modelTitle === '用户补券' ? supplycouponSupply : supplycouponCheck;
      const { code, data, msg } = await fatchApi({ ...values });
      if (code === 200) {
        modalNumForm.resetFields();
        setModelNumVisible(false);
        actionRef?.current?.reloadAndRest?.();
        message.success('操作成功');
      } else {
        message.error(msg || '操作失败');
      }
      setConfirmLoad(false);
    });
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.SupplycouponListItem>
          manualRequest={true}
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />
        <Modal
          title={modelTitle}
          width={520}
          open={modelNumVisible}
          onOk={handleNumOK}
          okText={modelText}
          onCancel={handleNumCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalNumForm}
            initialValues={{
              activityId: '',
              placeChannelId: '',
              activity: '',
              salePrice: '',
              discount: '',
              mobile: '',
              advanceStartTime: false,
            }}
          >
            <Form.Item label="activityId" name="activityId" style={{ width: 400 }} hidden>
              <Input />
            </Form.Item>

            <Form.Item label="placeChannelId" name="placeChannelId" style={{ width: 400 }} hidden>
              <Input />
            </Form.Item>

            <Form.Item label="券名" name="activity" style={{ width: 400 }}>
              <Input disabled />
            </Form.Item>

            {isCouponFalg && (
              <>
                <Form.Item label="顾客购买金额" name="salePrice" style={{ width: 400 }}>
                  <Input />
                </Form.Item>

                <Form.Item label="第三补贴金额" name="discount" style={{ width: 400 }}>
                  <Input />
                </Form.Item>
              </>
            )}

            <Form.Item
              label="手机号码"
              name="mobile"
              style={{ width: 400 }}
              rules={[
                {
                  required: true,
                  message: '不得为空',
                },
                {
                  validator: (_, value) => {
                    const regex = /^1[3-9]\d{9}$/;
                    if (!regex.test(value)) return Promise.reject(new Error('请检查手机号码格式'));
                    return Promise.resolve();
                  },
                },
              ]}
            >
              <Input />
            </Form.Item>

            {modelText && modelText === '确认补券' && (
              <Form.Item label="提前开始时间" name="advanceStartTime" style={{ width: 400 }}>
                <Radio.Group
                  options={[
                    { label: '否', value: false },
                    { label: '是', value: true },
                  ]}
                />
              </Form.Item>
            )}
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default SensitizeManageList;
